package com.ipoint.icompany.service;

import javax.persistence.EntityManager;
import javax.persistence.NoResultException;

import org.jboss.seam.annotations.In;
import org.jboss.seam.annotations.Name;
import org.jboss.seam.annotations.Out;
import org.jboss.seam.annotations.Transactional;
import org.jboss.seam.security.Identity;

import com.ipoint.icompany.model.Person;

@Name("authenticationService")
public class AuthenticationService {
	@In
	private EntityManager entityManager;
	@In
	private Identity identity;

	@Out(value = Person.CURRENT_PERSON, required = false)
	private Person currentPerson;

	public Person getCurrentPerson() {
		return currentPerson;
	}

	public void setCurrentPerson(Person currentPerson) {
		this.currentPerson = currentPerson;
	}

	@Transactional
	public boolean authenticate() {
		try {
			currentPerson = (Person) entityManager
					.createQuery(
							"from Person p where p.username = :username and p.password = :password")
					.setParameter("username", identity.getUsername())
					.setParameter("password", identity.getPassword())
					.getSingleResult();
			identity.addRole(currentPerson.getUsername());
			return true;
		} catch (NoResultException e) {
			return false;
		}
	}
}
